package com.qing.demo.netty.client;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.qing.demo.netty.domain.Constants;
import com.qing.demo.netty.domain.FileBurstData;
import com.qing.demo.netty.domain.FileBurstInstruct;
import com.qing.demo.netty.domain.FileTransferProtocol;
import com.qing.demo.netty.util.FileUtil;
import com.qing.demo.netty.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;


/**
 * @author caozhipeng
 * @date 2025/7/25
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel=(SocketChannel)ctx.channel();
        System.out.println("客户端链接报告开始！");
        System.out.println("客户端链接报告信息：本客户端链接到服务器。ChannelID="+socketChannel.id());
        System.out.println("客户端链接报告结束！");

//        String msg = "通知服务端，客户端链接建立成功！"+ DateUtil.date();
//        ctx.writeAndFlush(MsgUtil.buildMsg(socketChannel.id().toString(),msg));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开链接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        数据格式验证
        System.out.println("客户端收到："+JSONUtil.toJsonStr(msg));
        if(!(msg instanceof FileTransferProtocol))return;

        FileTransferProtocol fileTransferProtocol= (FileTransferProtocol) msg;
//        0 传输文件‘请求’ 1文件传输‘指令’ 2文件传输‘数据’
        switch (fileTransferProtocol.getTransferType()){
            case 1:
                FileBurstInstruct fileBurstInstruct= (FileBurstInstruct) fileTransferProtocol.getTransferObj();
                if(Constants.FileStatus.COMPLETE==fileBurstInstruct.getStatus()){
                    ctx.flush();
                    ctx.close();
                    System.exit(-1);
                    return;
                }
                FileBurstData fileBurstData= FileUtil.readFile(fileBurstInstruct.getClientFileUrl(),fileBurstInstruct.getReadPosition());
                ctx.writeAndFlush(MsgUtil.buildTransferData(fileBurstData));
                System.out.println("发送时间："+DateUtil.date()+" 发送文件：--->"+JSONUtil.toJsonStr(fileBurstData));
                break;
            default:
                break;
        }
        /**模拟传输过程中断，场景测试可以注释掉
         *
         */
//        System.out.println(DateUtil.date()+" bugstack虫洞栈客户端传输文件信息[主动断开链接，模拟断点续传]");
//        ctx.flush();
//        ctx.close();
//        System.exit(-1);

    }
}
